﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using PivotIO.XML;
using PivotWebsite.MediaFormatters;
using System.Configuration;
using System.IO;
using System.Threading;

namespace PivotWebsite.Tests.Controllers
{
    public class Utils
    {
        /// <summary>
        /// Get a PNG file
        /// </summary>
        /// <returns></returns>
        public static ImageFormatter.BinaryImage GetPng()
        {
            var fi = new FileInfo(@"test.png");
            Assert.IsTrue(fi.Exists, "png file missing");
            using (var fs = fi.OpenRead())
            {
                var r = new ImageFormatter.BinaryImage();
                r.metaData = "png";
                r.data = new byte[fi.Length];
                fs.Read(r.data, 0, (int)fi.Length);
                return r;
            }
        }

        /// <summary>
        /// Setup for a test.
        /// </summary>
        public static void TestInit()
        {
            ImageInfoIO.WaitTillIOFlushed();
            FacetCategoryIO.WaitTillIOFlushed();

            // Delete all data files!
            var dir = new DirectoryInfo(ConfigurationManager.AppSettings["ROOTXMLDirectory"]);
            if (dir.Exists)
            {
                for (int i = 0; i < 20; i++)
                {
                    try
                    {
                        dir.Delete(true);
                        break;
                    }
                    catch { }
                    Thread.Sleep(50);
                }
            }
            CollectionInfoIO.ResetCache();
            ImageInfoIO.ResetCache();
            FacetCategoryIO.ResetCache();
        }

        public static void TestFinalize()
        {
            ImageInfoIO.WaitTillIOFlushed();
            FacetCategoryIO.WaitTillIOFlushed();
        }
    }
}
